package com.example.demo.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.Exception.ServiceException;
import com.example.demo.entity.Admin;
import com.example.demo.entity.User;
import com.example.demo.service.IAdminService;
import com.example.demo.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * JWT拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    private static final String ERROR_CODE_401 = "401";

    @Autowired
    private IAdminService adminService;
    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(ERROR_CODE_401, "无token，请重新登录");
        }
        // 获取 token 中的adminId
        String role;
        String adminId;
        Admin admin;
        User user;
        try {
            DecodedJWT jwt = JWT.decode(token);
            adminId = jwt.getAudience().get(0);
            role = jwt.getClaim("role").asString();
            if ("admin".equals(role)) {
                // 如果角色是管理员，则从管理员表中查询管理员信息
                admin = adminService.getById(Integer.parseInt(adminId));
                if (admin == null) {
                    throw new ServiceException(ERROR_CODE_401, "用户不存在，请重新登录");
                }
                // 用户密码加签验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
                jwtVerifier.verify(token); // 验证token
            } else if ("user".equals(role)) {
                // 如果角色是普通用户，则从用户表中查询用户信息
                user = userService.getById(Integer.parseInt(adminId));
                if (user == null) {
                    throw new ServiceException(ERROR_CODE_401, "用户不存在，请重新登录");
                }
                // 用户密码加签验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                jwtVerifier.verify(token); // 验证token
            } else {
                // 未知角色，抛出异常
                throw new ServiceException(ERROR_CODE_401, "无效的角色，请重新登录");
            }
        } catch (JWTVerificationException e) {
            throw new ServiceException(ERROR_CODE_401, "token验证失败，请重新登录");
        }
        return true;
    }
}

